#include "mailserver.h"
#include "ui_mailserver.h"
#include "ui_addsmtp.h"
#include "common.h"
#include "../../libjson/libjson.h"
#include "url_string.h"
#include <QMessageBox>

extern std::string      g_token;
extern std::string      g_url;

MailServer::MailServer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MailServer)
{
    ui->setupUi(this);
    // 设置数据模型
    ui->tableView->setModel(&m_model);
    // 设置选中时为整行
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    // 设置表格的单元为只读属性，即不能编辑
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // 设置为单选
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    // 设置只能输入数字
    QValidator *validator=new QIntValidator(0,9999,this);
    ui->page_index->setValidator(validator);

    updateSmtps(0);
}

MailServer::~MailServer()
{
    delete ui;
}

void MailServer::initHeader()
{
    wchar_t*    heads[][2]  = { {L"邮箱", (wchar_t*)200}, {L"smtp", (wchar_t*)150},
                                {L"pop", (wchar_t*)150}, {L"用户名", (wchar_t*)200},
                                {L"密码", (wchar_t*)200}, {NULL, 0} };

    m_model.clear();
    // 设置标题
    for(int i = 0; NULL != heads[i][0]; i++)
    {
        m_model.setHorizontalHeaderItem(i, new QStandardItem(QString::fromWCharArray(heads[i][0])));
        ui->tableView->setColumnWidth(i, (int)(long)heads[i][1]);
    }
}

void MailServer::updateSmtps(int page)
{
    url_string<>        url;
    QString             err;
    JSONNode            json;
    int                 count   = 0;
    int                 page_size = PAGE_SIZE;

    // 创建头部
    initHeader();
    // 获取数据
    url.format("%s?handler=email&token=%u&size=%d&s=%u&page=%d",
               g_url.c_str(), g_token.c_str(), page_size,
               m_search.c_str(), page);
    // 请求网页
    if(false == ad::http_request(url.c_str(), err, &json))
    {
        QMessageBox     msg(this);

        msg.setText(err);
        msg.setIcon(QMessageBox::Critical);
        msg.exec();
        return;
    }

    // 解析数据
    if(false == ad::json_is_array(json, "data"))
    {
        return;
    }

    count = ad::json_get_int(json, "all", 0);
    page = ad::json_get_int(json, "page_cur", 0);
    page_size = ad::json_get_int(json, "page_size", 0);
    if( ad::json_is_array(json, "data") )
    {
        JSONNode&       arr     = json["data"];

        for( json_index_t i = 0; i < arr.size(); i++)
        {
            if( false == ad::json_is_array(arr, i) )
            {
                continue;
            }

            JSONNode&   item = arr[i];
            for(json_index_t k = 0; k < item.size() && k < 5; k++)
            {
                m_model.setItem(i, k,
                    new QStandardItem(ad::json_get_string(item, k)));
            }
        }
    }

    showNavigate(page, count, page_size);
}

void MailServer::showNavigate(int page, int all, int pagesize)
{
    wchar_t        buf[1024];

    if(0 == all)
    {
        ui->navigate->setEnabled(false);
        return;
    }

    ui->navigate->setEnabled(true);
    swprintf(buf, sizeof(buf) - 1, L"%d", page + 1);
    ui->page_index->setText(QString::fromWCharArray(buf));

    swprintf(buf, sizeof(buf) - 1, L"/%d页", (all + pagesize - 1) / pagesize);
    ui->page_all->setText(QString::fromWCharArray(buf));

    swprintf(buf, sizeof(buf) - 1, L"共有记录<font color=red>%d</font>条", all);
    ui->page_record->setText(QString::fromWCharArray(buf));

    bool        first   = (0 >= page);
    bool        last    = (page >= ((all + pagesize - 1) / pagesize - 1));

    ui->nvg_first->setEnabled(!first);
    ui->nvg_pre->setEnabled(!first);
    ui->nvg_next->setEnabled(!last);
    ui->nvg_last->setEnabled(!last);
    ui->page_index->setEnabled(!(first && last));
}

int MailServer::getCurPage()
{
    return ui->page_index->text().toInt();
}

void MailServer::onAdd()
{
    QDialog         dlg(this);
    Ui::AddSmtp     addsmtp;

    addsmtp.setupUi(&dlg);
    // 等待用户输入
    dlg.setWindowTitle(_T("添加新的邮件服务器"));
    while(true)
    {
        if(0 == dlg.exec())
        {
            return;
        }

        // 判断输入的完整性
        if(0 == addsmtp.email->text().length()
                || 0 == addsmtp.smtp->text().length()
                || 0 == addsmtp.smtp_port->text().length()
                || 0 == addsmtp.pop->text().length()
                || 0 == addsmtp.pop_port->text().length()
                || 0 == addsmtp.user->text().length()
                || 0 == addsmtp.pwd->text().length())
        {
            addsmtp.error->setText(_T("<font color=red>请输入完整的信息</font>"));
            continue;
        }

        // 添加到服务器
        url_string<>        url;
        url_string<>        post;
        QByteArray          byte;
        QString             err;

        url.format("%s?Handler=addemail&token=%u", g_url.c_str(), g_token.c_str());
        post.format("email=%u&smtp=%u&smtp_port=%d&pop=%u&pop_port=%d&user=%u&pwd=%u",
                    addsmtp.email->text().toUtf8().data(),
                    addsmtp.smtp->text().toUtf8().data(),
                    addsmtp.smtp_port->text().toInt(),
                    addsmtp.pop->text().toUtf8().data(),
                    addsmtp.pop_port->text().toInt(),
                    addsmtp.user->text().toUtf8().data(),
                    addsmtp.pwd->text().toUtf8().data() );
        byte.append(post.c_str(), post.length());
        if(false == ad::http_request(url.c_str(), err, NULL, this, &byte))
        {
            addsmtp.error->setText("<font color=red>" + err + "</font>");
            continue;
        }

        break;
    }

    // 添加成功需要更新数据
    updateSmtps(getCurPage() - 1);
}

void MailServer::onEdit()
{
    QItemSelectionModel*    selection = ui->tableView->selectionModel();
    QModelIndexList         list      = selection->selectedIndexes();

    if(0 == list.count())
    {
        QMessageBox     box(this);

        box.setIcon(QMessageBox::Critical);
        box.setText(_T("请选择要编辑的邮件服务器"));
        box.exec();
        return;
    }

    // 开始编辑
    QDialog         dlg(this);
    Ui::AddSmtp     editsmtp;
    QString         email       = m_model.item(list.at(0).row(), 0)->text();
    QString         smtp        = m_model.item(list.at(0).row(), 1)->text();
    QString         pop         = m_model.item(list.at(0).row(), 2)->text();
    QString         user        = m_model.item(list.at(0).row(), 3)->text();
    QString         pwd         = m_model.item(list.at(0).row(), 4)->text();
    QStringList     arr1        = smtp.split(':');
    QStringList     arr2        = pop.split(':');

    editsmtp.setupUi(&dlg);
    // 设置默认值
    editsmtp.email->setText(email);
    editsmtp.email->setDisabled(true);
    editsmtp.smtp->setText(arr1.at(0));
    editsmtp.smtp_port->setText(arr1.at(1));
    editsmtp.pop->setText(arr2.at(0));
    editsmtp.pop_port->setText(arr2.at(1));
    editsmtp.user->setText(user);
    editsmtp.pwd->setText(pwd);
    // 显示编辑框
    dlg.setWindowTitle(_T("编辑邮件服务器"));
    while(true)
    {
        if(0 == dlg.exec())
        {
            return;
        }

        // 判断输入的完整性
        if(0 == editsmtp.email->text().length()
                || 0 == editsmtp.smtp->text().length()
                || 0 == editsmtp.smtp_port->text().length()
                || 0 == editsmtp.pop->text().length()
                || 0 == editsmtp.pop_port->text().length()
                || 0 == editsmtp.user->text().length()
                || 0 == editsmtp.pwd->text().length())
        {
            editsmtp.error->setText(_T("<font color=red>请输入完整的信息</font>"));
            continue;
        }

        // 添加到服务器
        url_string<>        url;
        url_string<>        post;
        QByteArray          byte;
        QString             err;

        url.format("%s?Handler=modifyemail&token=%u", g_url.c_str(), g_token.c_str());
        post.format("email=%u&smtp=%u&smtp_port=%d&pop=%u&pop_port=%d&user=%u&pwd=%u",
                    editsmtp.email->text().toUtf8().data(),
                    editsmtp.smtp->text().toUtf8().data(),
                    editsmtp.smtp_port->text().toInt(),
                    editsmtp.pop->text().toUtf8().data(),
                    editsmtp.pop_port->text().toInt(),
                    editsmtp.user->text().toUtf8().data(),
                    editsmtp.pwd->text().toUtf8().data() );
        byte.append(post.c_str(), post.length());
        if(false == ad::http_request(url.c_str(), err, NULL, this, &byte))
        {
            editsmtp.error->setText("<font color=red>" + err + "</font>");
            continue;
        }

        break;
    }

    // 添加成功需要更新数据
    updateSmtps(getCurPage() - 1);
    // 重新选择
    ui->tableView->selectRow(list.at(0).row());
}

void MailServer::onDelete()
{
    QItemSelectionModel*    selection = ui->tableView->selectionModel();
    QModelIndexList         list      = selection->selectedIndexes();

    if(0 == list.count())
    {
        QMessageBox     box(this);

        box.setIcon(QMessageBox::Critical);
        box.setText(_T("请选择要删除的邮件服务器"));
        box.exec();
        return;
    }

    // 确认操作
    QMessageBox         confirm(this);
    QString             email       = m_model.item(list.at(0).row(), 0)->text();

    confirm.setIcon(QMessageBox::Question);
    confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    confirm.setText(_T("确实要删除\"") + email + _T("\"吗？"));
    if(QMessageBox::Yes != confirm.exec())
    {
        return;
    }
    // 执行删除
    url_string<>        url;
    QString             err;

    url.format("%s?Handler=deleteemail&token=%u&email=%u", g_url.c_str(), g_token.c_str(),
               email.toUtf8().data());
    if(false == ad::http_request(url.c_str(), err, NULL))
    {
        QMessageBox     box(this);

        box.setIcon(QMessageBox::Critical);
        box.setText(_T("删除失败:") + err);
        box.exec();
        return;
    }

    updateSmtps(getCurPage() - 1);
}

void MailServer::onRefresh()
{
    updateSmtps(getCurPage() - 1);
}

void MailServer::onTest()
{

}

void MailServer::onFirst()
{
     updateSmtps(0);
}

void MailServer::onPrev()
{
    updateSmtps(getCurPage() - 2);
}

void MailServer::onNext()
{
    updateSmtps(getCurPage());
}

void MailServer::onLast()
{
    updateSmtps(0x7ffffff);
}
